import { MenuOutlined, LogoutOutlined, UserOutlined, SearchOutlined, BookOutlined, UnorderedListOutlined, ScheduleOutlined, PlusOutlined } from "@ant-design/icons";
import { Avatar, Button, Drawer, Dropdown, Layout, Menu, message, Input } from "antd";
import { useState, useCallback, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { RootState } from "../../store";
import notLoginImg from "./notLogin.png";
import { logout } from "../../api/userController";
import { DEFAULT_USER, setLoginUser } from "../../store/loginUser";
import { MenuHeaderRouter } from "../../constant/MenuHeader";
import { LightMember } from "@icon-park/react";
import { debounce } from 'lodash';
import { listBookByPage } from "../../api/bookController";
import type { BookType } from "../../types/book";

const { Header } = Layout;
const { Search } = Input;

const HeaderComponent = () => {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [searchResults, setSearchResults] = useState<BookType[]>([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const [searchValue, setSearchValue] = useState("");

  // 获取菜单数据
  const menuItems = MenuHeaderRouter();

  // 退出登录
  const logoutUserInfo = async () => {
    const res = await logout();
    if (res.code === 200) {
      message.success("退出登录成功");
      dispatch(setLoginUser(DEFAULT_USER));
      navigate('/login');
    }
  };

  // 用户下拉菜单项
  const userMenuItems = [
    {
      key: "userinfo",
      icon: <UserOutlined />,
      label: "个人中心",
      onClick: () => navigate(`/userInfo/${loginUser.id}`),
    },
    {
      key: "myBooks",
      icon: <BookOutlined />,
      label: "我的借阅",
      onClick: () => navigate(`/my-books/${loginUser.id}`),
    },
    {
      key: "myBookList",
      icon: <UnorderedListOutlined />,
      label: "我的书单",
      onClick: () => navigate(`/my-booklist/${loginUser.id}`),
    },
    {
      key: "mySeat",
      icon: <ScheduleOutlined />,
      label: "我的座位",
      onClick: () => navigate(`/my-seat/${loginUser.id}`),
    },
    {
      key: "logout",
      icon: <LogoutOutlined />,
      label: "退出登录",
      onClick: logoutUserInfo,
    },
  ];

  // 节流处理的搜索函数
  const debouncedSearch = useMemo(
    () =>
      debounce(async (value: string) => {
        if (!value.trim()) {
          setSearchResults([]);
          return;
        }
        
        try {
          const response = await listBookByPage({
            current: 1,
            pageSize: 8,
            bookname: value,
            bookauthor: "",
            categorycode: ["all"]
          });
          
          if (response.code === 200) {
            setSearchResults(response.data.records);
          }
        } catch (error) {
          console.error('Search error:', error);
        }
      }, 300),
    []
  );

  // 处理搜索输入
  const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchValue(value);
    debouncedSearch(value);
    setSearchVisible(true);
  };

  // 处理选择搜索结果
  const handleSelectResult = (bookId: string) => {
    setSearchVisible(false);
    setSearchValue("");
    setSearchResults([]);
    navigate(`/book/${bookId}`);
  };

  // 高亮搜索关键词
  const highlightText = (text: string, keyword: string) => {
    if (!keyword.trim()) return text;
    const parts = text.split(new RegExp(`(${keyword})`, 'gi'));
    return (
      <span>
        {parts.map((part, index) => 
          part.toLowerCase() === keyword.toLowerCase() ? (
            <span key={index} className="text-red-400 font-medium">{part}</span>
          ) : (
            part
          )
        )}
      </span>
    );
  };

  // 替换原来的Search组件
  const searchComponent = (
    <div className="relative">
      <Input
        placeholder="搜索图书..."
        value={searchValue}
        onChange={handleSearchInput}
        onBlur={() => {
          // 使用setTimeout来确保点击事件能够先触发
          setTimeout(() => setSearchVisible(false), 200);
        }}
        onFocus={() => {
          if (searchValue) setSearchVisible(true);
        }}
        prefix={<SearchOutlined />}
        className="w-[300px]"
      />
      
      {searchVisible && searchResults.length > 0 && (
        <div className="absolute z-50 w-full mt-1 bg-white rounded-md shadow-lg max-h-[400px] overflow-y-auto">
          {searchResults.map((book) => (
            <div
              key={book.id}
              className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
              onClick={() => handleSelectResult(book.id)}
            >
              <div className="flex items-center">
                <img 
                  src={book.imageurl} 
                  alt={book.bookname}
                  className="w-10 h-10 object-cover rounded mr-2"
                />
                <div>
                  <div className="font-medium">
                    {highlightText(book.bookname, searchValue)}
                  </div>
                  <div className="text-sm text-gray-500">
                    {book.bookauthor}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  return (
    <Header className="bg-white px-4 flex items-center h-16 shadow-sm">
      {/* 移动端菜单按钮 */}
      <Button
        className="lg:hidden mr-2"
        type="text"
        icon={<MenuOutlined />}
        onClick={() => setDrawerVisible(true)}
      />

      {/* Logo和标题 */}
      <div className="flex items-center">
        <img
          src="https://xinggui-1311139524.cos.ap-guangzhou.myqcloud.com/logo.png"
          alt="logo"
          className="h-8 cursor-pointer"
          onClick={() => navigate("/home")}
        />
        <span 
          className="ml-2 text-xl font-bold cursor-pointer hidden sm:block"
          onClick={() => navigate("/home")}
        >
          星轨-图书借阅
        </span>
      </div>

      {/* 桌面端菜单 - 修改定位和响应式控制 */}
      <div className="hidden lg:flex ml-10">
        <Menu 
          mode="horizontal" 
          className="border-none"
          items={menuItems.map(item => ({
            ...item,
            key: item.path,
            label: item.name,
            onClick: () => navigate(item.path),
          }))}
          selectedKeys={[location.pathname]}
          style={{
            backgroundColor: 'transparent',
          }}
        />
      </div>

      {/* 右侧区域容器 */}
      <div className="flex items-center ml-auto">
        {/* 搜索框 - 桌面端 */}
        <div className="hidden md:block mr-4">
          {searchComponent}
        </div>

        {/* 新增帖子按钮 - 仅在宽度大于500px时显示 */}
        <div className="hidden min-[500px]:block mr-4">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/create-post')}
          >
            发帖
          </Button>
        </div>

        {/* 搜索图标 - 移动端 */}
        <div className="md:hidden mx-2">
          <Button
            type="text"
            icon={<SearchOutlined />}
            onClick={() => navigate('/search')}
          />
        </div>

        {/* 用户信息 */}
        <div className="flex items-center">
          {loginUser.id !== -1 ? (
            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <div className="flex items-center cursor-pointer">
                <Avatar src={loginUser.avatarUrl || notLoginImg} size="small" />
                <span className="ml-2 hidden sm:block">{loginUser.nickName}</span>
              </div>
            </Dropdown>
          ) : (
            <div 
              className="flex items-center cursor-pointer" 
              onClick={() => navigate("/login")}
            >
              <Avatar icon={<UserOutlined />} size="small" />
              <span className="ml-2">登录</span>
            </div>
          )}
        </div>
      </div>

      {/* 移动端抽屉菜单 */}
      <Drawer
        title="菜单导航"
        placement="left"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={250}
      >
        <Menu
          mode="inline"
          items={menuItems.map(item => ({
            ...item,
            key: item.path,
            label: item.name,
            onClick: () => {
              navigate(item.path);
              setDrawerVisible(false);
            },
          }))}
          selectedKeys={[location.pathname]}
        />
      </Drawer>
    </Header>
  );
};

export default HeaderComponent;
